
//
//  FeedbackViewController.swift
//  OnceNectar
//
//  Created by 法正磊 on 2018/3/1.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit
import IQKeyboardManagerSwift
import Networking
import Alamofire
import PKHUD
import SwiftyJSON

class FeedbackViewController: BaseViewController, AddCornerUIRectCorner, BottomShadow, UIImagePickerControllerDelegate,UITextViewDelegate {
    @IBOutlet weak var mainTextView: IQTextView!
    @IBOutlet weak var mainView: UIView!
    @IBOutlet weak var topVew: UIView!
    @IBOutlet weak var bottomView: UIView!
    @IBOutlet weak var phoneText: UITextField!
    @IBOutlet weak var img1: UIImageView!
    @IBOutlet weak var img2: UIImageView!
    @IBOutlet weak var img3: UIImageView!
    @IBOutlet weak var img4: UIImageView!
    @IBOutlet weak var img5: UIImageView!
    @IBOutlet weak var addImgBtn: UIButton!
    
    @IBOutlet weak var numLabel: UILabel!
    var joinid: String?
    var imgArray: Array<String>?
    override func viewDidLoad() {
        super.viewDidLoad()
        imgArray = Array()
        setUI()
        // Do any additional setup after loading the view.
    }
    
    func setUI() {
        titleLabel(text: "意见反馈", nil)
        setShadow(view: mainView, opacity: bottomShadowOpacity, size: bottomShadowOffset, color: UIColor.black, cornerradius: CORNERRADIUS)
        addCornerWithView(aView: topVew, aCorners: [.topLeft, .topRight], aSize: CGSize(width: CORNERRADIUS, height: CORNERRADIUS))
        addCornerWithView(aView: bottomView, aCorners: [.bottomLeft, .bottomRight], aSize: CGSize(width: CORNERRADIUS, height: CORNERRADIUS))
        
    }
    
    override func setNavigation() {
        let button = UIButton(type: .custom)
        button.setTitle("提交", for: .normal)
        button.setTitleColor(UIColor.white, for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        button.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
        button.addTarget(self, action: #selector(submit), for: .touchUpInside)
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
    }
    
    @objc func submit() {
        if let count = phoneText.text?.count, count < 8 {
            self.showToast(msg:"请填写手机号")
            return
        }
        if let count = mainTextView.text?.count, count < 1 {
            self.showToast(msg:"请填写内容")
            return
        }
        if let id = self.joinid {
            var parameters = ["mp": phoneText.text!, "suggestion": mainTextView.text!]
            if (self.joinid != nil) {
                parameters  = ["mp": phoneText.text!, "suggestion": mainTextView.text!, "imagesJointId":self.joinid!]
            }
            
            let requesturl = "http://www.1du.me/miwebproj/api/feedback"
            
            Alamofire.request(requesturl, method: .post,
                              parameters:  parameters,
                              encoding: URLEncoding.default,
                              headers: ["token":MineInfoModel.share.token!]).responseJSON {
                                (response) in
                                HUD.hide()
                                if(response.error == nil){
                                    if let result = response.result.value as? NSDictionary
                                    {
                                        let json = JSON(result)
                                        if json["code"].int == 1 {
                                            self.showToast(msg: json["message"].string!)
                                            self.navigationController?.popViewController(animated: true)
                                        }else {
                                            self.showToast(msg:json["message"].string!)
                                        }
                                    }
                                }
                                else{
                                    self.showToast(msg: "上传失败")
                                }

            }
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    @IBAction func selectPhoto(_ sender: Any) {
        let pick = UIImagePickerController()
        pick.delegate = self
        pick.sourceType = .photoLibrary
        pick.allowsEditing = false
        pick.mediaTypes = ["public.image"]
        self.present(pick, animated: true, completion: nil)

    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let image = info[UIImagePickerControllerOriginalImage]
        picker.dismiss(animated: true, completion: nil)
        let util = MMFileUploadUtil()
        util.uploadFile(with: UIImageJPEGRepresentation(image as! UIImage, 1), fs: "1", jointId: self.joinid) { (response, error) in
            if (error != nil) {
                self.showToast(msg:"上传失败")
            }
            else{
                let sudi: NSDictionary? = response as? NSDictionary
                let json = JSON(sudi)
                let joindata = json["data"].dictionary
                let join = joindata!["jointId"]
                let path = joindata!["filePath"]
                if self.joinid == nil {
                    self.joinid = join?.string
                }
                self.imgArray?.append((path?.string)!)
                let count = 10 + (self.imgArray?.count)!
                if count >= 11 {
                    var img :UIImageView = self.view.viewWithTag(count) as! UIImageView
                    let imgPath:String? = path?.string
                    let path:String = "\(BaseURL)\(imgPath!)"
                    let url = URL(string: path)
                    img.sd_setImage(with: url, completed: nil)
                }
                if self.imgArray?.count == 5 {
                    self.addImgBtn.isUserInteractionEnabled = false
                }
                
               self.showToast(msg:"上传成功")
            }
        }
        
    }
    func textViewDidChange(_ textView: UITextView) {
        
        if mainTextView.text.characters.count > 0 {
            
            //获得已输出字数与正输入字母数
            let selectRange = mainTextView.markedTextRange
            
            //获取高亮部分 － 如果有联想词则解包成功
            if let selectRange = selectRange {
                let position =  mainTextView.position(from: (selectRange.start), offset: 0)
                if (position != nil) {
                    return
                }
            }
            
            let textContent = mainTextView.text
            let textNum = textContent?.characters.count
            
            //截取200个字
            if textNum! > 300 {
                let index = textContent?.index((textContent?.startIndex)!, offsetBy: 300)
                let str = textContent?.substring(to: index!)
                mainTextView.text = str
            }
        }
        self.numLabel.text =  "\(mainTextView.text.characters.count)/\(300)"
    }
}
